<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="loadForm" class="demo-form-inline">
      <el-form-item label="分类名称">
        <el-input v-model="loadForm.typeName" size="small" clearable placeholder="分类名称" @clear="listPageData" @keyup.enter.native="listPageData" />
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" type="primary" size="mini" @click="listData">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" :loading="exportLoading" @click="handleExport">导出</el-button>
      </el-col> -->
    </el-row>

    <!-- 表格 -->
    <el-table
      :data="tableData"
      highlight-current-row
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="50" align="center" />

      <el-table-column label="分类名称" prop="typeName" align="center" />
      <el-table-column label="封面" prop="typeCoverUrl" align="center">
        <template slot-scope="scope">
          <el-image :src="scope.row.typeCoverUrl" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="totalCount > 0"
      :total="totalCount"
      :page.sync="loadForm.pageNum"
      :limit.sync="loadForm.pageSize"
      @pagination="listPageData"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">

        <el-form-item label="分类名称" prop="typeName">
          <el-input v-model="form.typeName" clearable placeholder="请输入分类名称" />
        </el-form-item>

        <el-form-item v-if="showUpdate()" label="封面" prop="typeCoverUrl" label-width="100px">
          <el-image
            style="width: 100%; height: auto;"
            :src="form.typeCoverUrl"
            fit="contain"
          />
        </el-form-item>

        <el-form-item v-if="showUpdate()" label="替换封面" label-width="100px">
          <el-upload
            class="avatar-uploader"
            action="#"
            drag
            :http-request="requestUpload"
            :show-file-list="false"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>

        <el-form-item v-if="!showUpdate()" label="封面" label-width="100px">
          <el-upload
            class="avatar-uploader"
            action="#"
            drag
            :http-request="requestUpload"
            :show-file-list="false"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>

        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import { load, saveOrUpdate, downExcel } from '@/api/video/type'
import { getDetail, remove } from '@/api/video/media-common-back.js'
import { uploadCover } from '@/api/video/video.js'
export default {
  name: 'AdMediaType',
  // 加载分页组件
  components: { Pagination },
  data() {
    return {
      // 表格数据
      tableData: [],
      // 默认当前页
      currentPage: 1,
      // 总页数
      totalCount: 0,
      // 导出遮罩层
      exportLoading: false,
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 弹出层标题
      title: '',
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // id集合
      ids: [],
      // 查询条件
      loadForm: {
        pageNum: 1,
        pageSize: 10,
        // 具体查询条件
        typeName: undefined
      },
      // 文件路径
      imageUrl: undefined,
      // 通用详情/删除条件
      commonForm: {
        id: undefined,
        idList: [],
        tableName: 'ad_media_type'
      }
    }
  },

  // 钩子函数
  created() {
    this.listPageData()
  },
  methods: {
    // 查询页面数据
    listPageData() {
      console.log('加载数据')
      load(this.loadForm).then(response => {
        this.tableData = response.data.records
        this.totalCount = response.data.total
      })
    },

    handleRemove(file, fileList) {
      // console.log(file, fileList)
    },

    // 是否为修改标签
    showUpdate() {
      return this.title === '修改'
    },

    // 覆盖默认的上传行为
    requestUpload() {
      console.log('处理上传')
      this.replaceCover()
    },

    // 替换图片
    replaceCover() {
      const data = this.filleData
      const formData = new FormData()
      formData.append('file', data)
      uploadCover(formData).then(res => {
        console.log('封面上传成功', res.data)
        this.imageUrl = res.data
      })
    },

    // 查询按钮操作
    listData() {
      this.listPageData()
    },

    beforeUpload(file) {
      console.log('上传前校验')
      // 上传前的校验，例如文件类型和大小
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      if (!isJPG && !isPNG) {
        this.$message.error('只能上传JPG/PNG文件!')
      }
      this.filleData = file
      return isJPG || isPNG
    },

    // 重置按钮操作
    resetQuery() {
      this.resetForm()
      this.listData()
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 新增修改表单重置
    reset() {
      this.form = {}
      this.imageUrl = undefined
    },

    // 重置查询表单
    resetForm() {
      this.loadForm = {}
    },

    // 表格多选操作
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      // 单选状态 值为true 可操作表单上方修改按钮
      this.single = selection.length !== 1
      // 选中数据后可放开删除按钮
      this.multiple = !selection.length
    },

    // 新增按钮操作
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加'
    },

    // 删除按钮操作
    handleDelete(row) {
      const id = row.id || this.ids
      console.log('id 集合', id)

      // 处理ID集合
      if (row.id) {
        this.commonForm.idList = [id]
      } else {
        this.commonForm.idList = id
      }

      this.$modal.confirm('是否确认删除？')
        .then(() => {
          console.log('删除')
          remove(this.commonForm).then(res => {
            this.$modal.msgSuccess('操作成功')
            this.listData()
          })
        })
    },

    // 修改按钮操作
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids[0]
      this.commonForm.id = id
      // 获取详情
      getDetail(this.commonForm).then(res => {
        this.form = res.data
        this.open = true
        this.title = '修改'
      })
    },

    // 提交按钮
    submitForm: function() {
      this.form.typeCoverUrl = this.imageUrl

      if (this.form.id === undefined) {
        console.log('新增')
        saveOrUpdate(this.form).then((response) => {
          this.$modal.msgSuccess('操作成功')
          console.log('后续处理')
          this.open = false
          this.listData()
          this.reset()
        })
      } else {
        console.log('修改')
        saveOrUpdate(this.form).then((response) => {
          this.$modal.msgSuccess('操作成功')
          console.log('后续处理')
          this.open = false
          this.listData()
          this.reset()
        })
      }
    },

    // 导出excel
    handleExport() {
      this.loadForm.idList = this.ids
      console.log('导出操作 ids', this.loadForm.idList)
      this.$modal.confirm('是否确认导出数据项？')
        .then(() => {
          // console.log('导出操作函数')
          this.exportLoading = true
          downExcel(this.loadForm)
            .then(response => {
              // 获取响应头中的文件名
              const fileName = decodeURIComponent(response.headers['content-disposition'].split('=')[1])
              // 创建URL对象并指定blob数据
              const url = window.URL.createObjectURL(new Blob([response.data]))
              // 创建a标签并设置下载属性
              const link = document.createElement('a')
              link.href = url
              // 设置下载文件名
              link.setAttribute('download', fileName)
              // 添加到页面中并触发点击事件进行下载
              document.body.appendChild(link)
              link.click()
              // 下载完成后移除a标签并释放URL对象
              document.body.removeChild(link)
              window.URL.revokeObjectURL(url)
              this.exportLoading = false
              this.listPageData()
            })
            .catch(error => {
              console.error('下载Excel失败: ', error)
            })
        })
    }

  }
}
</script>

<style>
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
